package bd;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.*;
import java.util.Scanner;
import javax.swing.JOptionPane;


public class MySQL {

    public static String status = "Não conectou...";
    public MySQL() {   }

public static java.sql.Connection getConexaoMySQL() {

    Connection connection = null;     //atributo do tipo Connection
    String driverName = "com.mysql.jdbc.Driver";
    String serverName = "localhost:3306";    //caminho do servidor do BD
    String mydatabase ="New BD";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
    String username = "root";         //nome de um usuário de seu BD
    String password = "11051608";        //sua senha de acesso


try {
         
    connection = DriverManager.getConnection(url, username, password);
    
    
} catch (SQLException e) {
            e.printStackTrace(); }
      
     return connection;
}

public static void consultar() {

       Statement s = null;
       Connection connection = MySQL.getConexaoMySQL();
       
       try {
           s = (Statement) connection.createStatement();
       } 
       
       catch (SQLException e) { e.printStackTrace(); }

       ResultSet r = null;

       try {
           
           r = s.executeQuery("Select * from Livros");

       } 
       
       catch (SQLException e) { e.printStackTrace(); }

       System.out.println("ID       NOME");

       try {

           while (r.next()){
               System.out.println(r.getInt("ID")+ "  " + r.getString("autor") + "\t" + r.getString("titulo"));
           }
           
       } catch (SQLException e) { e.printStackTrace(); }

       try {

           r.close();

       } catch (SQLException e) { e.printStackTrace(); }

}


public static void insereMidia (String ID, String autor, String titulo) {
        
    Scanner input = new Scanner( System.in );
    PreparedStatement ins = null;
    Connection connection = MySQL.getConexaoMySQL();
    
    try {

        ins = (PreparedStatement) connection.prepareStatement("INSERT INTO Livros (ID, autor, titulo, curso) VALUES (?,?,?,'Eng Comp')");
        ins.setString(1, ID);
        ins.setString(2, autor );
        ins.setString(3, titulo);

        int updateCount = ins.executeUpdate();

    }
        catch (SQLException e) { e.printStackTrace(); }

    }

}
